package com.zp.base.admin.security;

import com.alibaba.fastjson.JSON;
import com.zp.base.admin.common.constant.BizCodeEnum;
import com.zp.base.admin.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhangpeng
 * @create 2020/8/27 17:24
 */
@Component
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info ("onAuthenticationFailure ....");
        String message = e.getMessage ();

        if (message.equals ("User is disabled")){
            message = BizCodeEnum.ACCOUNT_DISABLE.getCode() + ":" + BizCodeEnum.ACCOUNT_DISABLE.getMsg();
        }

        if (message.equals ("Bad credentials")){
            message = BizCodeEnum.LOGIN_FAIL.getCode() + ":" + BizCodeEnum.LOGIN_FAIL.getMsg();
        }


        String[] split = message.split(":");
        String jsonStr = JSON.toJSONString(R.error(Integer.valueOf(split[0]), split[1]));

        httpServletResponse.setContentType ("application/json;charset=utf-8");
        httpServletResponse.getWriter ().print (jsonStr);

    }
}
